package com.xiaotu.spider.baidu.pageprocessor;

import com.xiaotu.common.model.TVStringModel;
import com.xiaotu.common.util.*;
import com.xiaotu.server.service.guduo.SupplementGuDuoRecordService;
import com.xiaotu.spider.AUrlPageProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类名 TVBaikeInfoPageProcessor
 * @日期 2021年2月22日
 * @作者 王艳龙
 * @功能 百度百科作品基本信息
 */
@Component("TVBaikeInfoPageProcessor")
public class TVBaikeInfoPageProcessor extends AUrlPageProcessor
{
    private String tv_url = "https://www.baidu.com/";

    @Autowired
	private SupplementGuDuoRecordService starService;
    
    @Override
	protected String[] getStartRequestUrls() {
    	return new String[]{tv_url};
	}
	
    @Override
   	public void process(Page page) {
    	if (Constants.PageDataType.STAR_RECORD.equals(this.getPageDataType(page)))
            this.tvRecord(page);
        else
            this.pageProcess(page);
    }
    
    private void pageProcess(Page page) {
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("rows",5000);
		param.put("page",1);
		List<Map<String,Object>> starList = starService.getAllTvInfoList(param);
		for (Map<String, Object> starInfoMap : starList) {
			String linkUrl = "https://baike.baidu.com/item/"+ KeywordEncode.encode(starInfoMap.get("tvname")+"")+"?" +
					"tvid="+starInfoMap.get("tvid")+"&actor="+KeywordEncode.encode(starInfoMap.get("actor")+"")+
					"&director="+KeywordEncode.encode(starInfoMap.get("director")+"")+
					"&screen="+KeywordEncode.encode(starInfoMap.get("screenwriter")+"");
			PageUtils.addTargetRequest(page, linkUrl, page.getRequest().getExtras());
		}
    }

	private void tvRecord(Page page) {
		String linkUrl = KeywordEncode.decode(page.getUrl().toString());
		String tvName = null;
		String tvId = null;
		String resActor=null;
		String resDirector = null;
		String resScreen = null;
		tvName = linkUrl.substring(linkUrl.indexOf("item/")+5, linkUrl.indexOf("?tvid"));
		tvId = linkUrl.substring(linkUrl.indexOf("tvid=")+5, linkUrl.indexOf("&actor"));
		resActor = linkUrl.substring(linkUrl.indexOf("actor=")+6, linkUrl.indexOf("&director"));
		resDirector = linkUrl.substring(linkUrl.indexOf("director=")+9, linkUrl.indexOf("&screen"));
		resScreen = linkUrl.substring(linkUrl.indexOf("screen=")+7, linkUrl.length());

		List<String> ddList = page.getHtml().xpath("//div[@class='basic-info']/dl/dd").all();
		List<String> dtList = page.getHtml().xpath("//div[@class='basic-info']/dl/dt/text()").all();
		if(dtList.size()==0){
			dtList= page.getHtml().xpath("//div[@id='baseInfoWrapDom']/div/div/div/span/text()").all();
			ddList = page.getHtml().xpath("//div[@id='baseInfoWrapDom']/div/div/div/div[@class='biContent']").all();

			if(dtList.size()==0){
				return;
			}
		}

		String actor=null,director=null,screenwriter=null;
		for(int i=0;i<dtList.size();i++) {
			String dt = dtList.get(i);
			if (dt.contains("主") && dt.contains("演")) {
				actor = ddList.get(i);
			}
			if (dt.contains("导") && dt.contains("演")) {
				director = ddList.get(i);
			}
			if (dt.contains("编") && dt.contains("剧")) {
				screenwriter = ddList.get(i);
			}
		}
			//规则匹配，演员、导演、编剧只要有一个成立，获取基本信息
			if(getSplitActor(resActor,actor) ||
				getSplitActor(resDirector,director) ||
				getSplitActor(resScreen,screenwriter)) {
				TVStringModel model = new TVStringModel();
				model.setTvid(tvId);
				model.setTvname(tvName);
				for (int i = 0; i < dtList.size(); i++) {
					String dt = DBArrayUtils.getArrayString(getTextByHtml(dtList.get(i)).replace("&nbsp;", ""));
					switch (dt) {
						case "别名":
							model.setAlias(DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", "")));
							break;
						case "其他译名":
							model.setAlias(DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", "")));
							break;
						case "类型":
							model.setShowtype(DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", "")));
							break;
						case "出品公司":
							model.setSellcompany(DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", "")));
							break;
						case "制片地区":
							model.setArea(DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", "")));
							break;
						case "拍摄日期":
							String shootDates = DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", ""));
							//shootDates = shootDates.replace("年","-").replace("月","-").replace("份","").replace("日","");
							//shootDates = shootDates.substring(0,shootDates.lastIndexOf("-"));
							model.setShootdate(shootDates);
							break;
						case "拍摄地点":
							model.setShootaddress(DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", "")));
							break;
						case "发行公司":
							model.setIssuingcompany(DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", "")));
							break;
						case "导演":
							model.setDirector(DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", "")));
							break;
						case "编剧":
							model.setScreenwriter(DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", "")));
							break;
						case "制片人":
							model.setProducer(DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", "")));
							break;
						case "主演":
							model.setActor(DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", "")));
							break;
						case "片长":
							model.setTimelength(RegexUtils.regexSearch(RegexUtils.REGEX_NUMBER, DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", ""))));
							break;
						case "每集长度":
							model.setTimelength(RegexUtils.regexSearch(RegexUtils.REGEX_NUMBER, DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", ""))));
							break;
						case "出品时间":
							String releasetimes = DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", ""));
							if(StringUtil.isNotEmpty(releasetimes)){
								releasetimes =releasetimes.substring(0,4);
								model.setReleasetime(releasetimes);
							}
							break;
						case "在线播放平台":
							model.setPlatform(DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", "")));
							break;
						case "上映时间":
							String firstTime1 = DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", ""));
								//firstTime1 =firstTime1.replaceAll("年","-").replaceAll("月","-").replaceAll("日","");
								//firstTime1 = firstTime1.substring(0,firstTime1.lastIndexOf("-"));
								model.setFirstplaytime(firstTime1);
							break;
						case "首播时间":
							String firstTime2 = DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", ""));
								//firstTime2 =firstTime2.replaceAll("年","-").replaceAll("月","-").replaceAll("日","");
								//firstTime2 = firstTime2.substring(0,firstTime2.lastIndexOf("-"));
								model.setFirstplaytime(firstTime2);
							break;
						case "集数":
							model.setSets(RegexUtils.regexSearch(RegexUtils.REGEX_NUMBER, DBArrayUtils.getArrayString(getTextByHtml(ddList.get(i)).replace("&nbsp;", ""))));
							break;
						default:
							break;
					}
				}
					page.putField(TVStringModel.class.getName(), model);
			}
    }

	public boolean getSplitActor(String resActor,String actor){
		boolean actorflag = false;
		if(StringUtil.isNotEmpty(resActor)){
			String[] actorArr = resActor.split(",");
			for (String actorStr : actorArr) {
				if(StringUtil.isNotEmpty(actor)){
					if(actor.contains(actorStr)){
						actorflag = true;
						break;
					}
				}
			}
		}
		return actorflag;
	}

	/**
	 * 解析Baidu电视剧基本信息的dt和dd
	 * @param htmlStr
	 * @return
	 */
	public String getTextByHtml(String htmlStr){
		//过滤Baidu的标签
		while(htmlStr.contains("<sup>")){
			String before = htmlStr.substring(0,htmlStr.indexOf("<sup>"));
			String after = htmlStr.substring(htmlStr.indexOf("</sup>")+6,htmlStr.length());
			htmlStr=before+after;
		}
		return HtmlUtil.delHTMLTagBak(htmlStr);
	}
    
	@Override
	protected String getSpiderType() {
		return Constants.SpiderTaskType.TV_BAIKE_INFO;
	}

	@Override
	public String getPageDataType(Page page) {
		String url = page.getUrl().toString();
        if (url.contains("item"))
        	return Constants.PageDataType.STAR_RECORD;
		return Constants.PageDataType.SEARCH_LIST;
	}
}
